package com.example.tangjiangxu.contactsgroupdemo;

import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AlphabetIndexer;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private Button btnAlpabet;
    private RelativeLayout rlSectionToast;
    private TextView tvSectionToast;
    /** 分组的布局 **/
    private LinearLayout llTitle;
    /** 分组上显示的字母 **/
    private TextView tvTitle;
    /** 联系人ListView **/
    private ListView lvContacts;
    /** 联系人列表适配器 **/
    private ContactAdapter adapter;
    /** 用于进行字母表分组 **/
    private AlphabetIndexer indexer;
    /** 存储在所有手机中的联系人 **/
    private List<Contact> contactList = new ArrayList<Contact>();
    /** 定义字母表的排序规则 **/
    private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /** 上次第一个可见元素，用于滚动时记录标示 **/
    private int lastFirstVisibleItem = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnAlpabet = (Button) findViewById(R.id.btn_alphabet);
        rlSectionToast = (RelativeLayout) findViewById(R.id.rl_section_toast);
        tvSectionToast = (TextView) findViewById(R.id.tv_section_toast);
        adapter = new ContactAdapter(this, R.layout.contacts_item, contactList);
        llTitle = (LinearLayout) findViewById(R.id.ll_title);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        lvContacts = (ListView) findViewById(R.id.lv_contacts);
        Uri uri = Uri.parse("content://com.android.contacts/contacts");
        //new String[] {"display_name", "sort_key"}
        //Android 4.4以后，sort_Key改为phonebook_label
        Cursor cursor = getContentResolver().query(uri, new String[] {"display_name", "phonebook_label" }, null, null, "phonebook_label");
        if (cursor.moveToFirst()) {
            do {
                String name = cursor.getString(0);
                String sortKey = cursor.getString(1);
                //sort_Key来查找，为Tang 唐，  phonebook_label来查找，直接为T
                //sortKey = getSortKey(sortKey);
                Contact contact = new Contact();
                contact.setName(name);
                contact.setSortKey(sortKey);
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
        startManagingCursor(cursor);
        indexer = new AlphabetIndexer(cursor, 1, alphabet);
        adapter.setIndexer(indexer);
        if (contactList.size() > 0) {
            setupContactsList();
            setAlpabetListener();
        }
    }

    /**
     * 设置字母表的监听事件
     */
    private void setAlpabetListener() {
        btnAlpabet.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float alphabetHeight = btnAlpabet.getHeight();
                float y = event.getY();
                int sectioinPosition = (int) ((y * 1.0 / alphabetHeight) * 27.0);
                Log.e(TAG, "onTouch: sectioinPosition"  + sectioinPosition);
                if (sectioinPosition < 0) {
                    sectioinPosition = 0;
                } else if (sectioinPosition > 26){
                    sectioinPosition = 26;
                }
                String sectionLetter = alphabet.charAt(sectioinPosition) + "";
                int postion = indexer.getPositionForSection(sectioinPosition);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        btnAlpabet.setBackgroundResource(R.drawable.a_z_click);
                        rlSectionToast.setVisibility(View.VISIBLE);
                        tvSectionToast.setText(sectionLetter);
                        lvContacts.setSelection(postion);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        tvSectionToast.setText(sectionLetter);
                        lvContacts.setSelection(postion);
                        break;
                    default:
                        btnAlpabet.setBackgroundResource(R.drawable.a_z);
                        rlSectionToast.setVisibility(View.GONE);
                        break;
                }
                return true;
            }
        });



    }

    /**
     * 为联系人Listview设置监听事件，根据当前的华东状态来改变分组的显示位置，从而实现挤压动画的效果
     */
    private void setupContactsList() {
        lvContacts.setAdapter(adapter);
        lvContacts.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            /**
             * 默认会调用一次
             * @param view 滑动所属的View，这里为ListView
             * @param firstVisibleItem 第一个可见条目的位置
             * @param visibleItemCount 可见条目的数量，一般为一屏所见条目或者＋1个
             * @param totalItemCount 总数量
             */
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //Log.e(TAG, "onScroll: firstVisibleItem：" + firstVisibleItem + ",visibleItemCount:" + visibleItemCount + ",totalItemCount:" + totalItemCount);
                //当前屏幕第一个条目，所在分组位置，比如A-1
                int section = indexer.getSectionForPosition(firstVisibleItem);
                //下一个分组，所在屏幕位置，比如B-10
                int nextSecPostion = indexer.getPositionForSection(section + 1);
                //判断当前第一个位置是否和上一次第一个条目的位置，如果不想等，则改变标题显示内容
                if (firstVisibleItem != lastFirstVisibleItem) {
                    Log.e(TAG, "firstVisibleItem:" + firstVisibleItem + ",lastFirstVisibleItem:" + lastFirstVisibleItem);
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) llTitle.getLayoutParams();
                    params.topMargin = 0;
                    llTitle.setLayoutParams(params);
                    tvTitle.setText(alphabet.charAt(section) + "");
                }
                //如果下一个分组所在屏幕位置等于当前第一个屏幕位置＋1，即上滑挤压
                if (nextSecPostion == firstVisibleItem + 1) {
                    //这里的childView为ListView可见区域的第一个Item,这时候已经显示不全了
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        //标题栏的高度
                        int titleHeight = llTitle.getHeight();
                        //ListView的第一个Item的bottom位置，这里是针对Listview的bottom位置。
                        int bottom = childView.getBottom();
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) llTitle.getLayoutParams();
                        if (bottom < titleHeight) { //这时候ListView的第一个条目，全部被Title栏覆盖
                            //Title布局需要topMargin的距离。刚开始，bottom为Title布局的高度，所以为0，这时候，Titile布局完全显示；最后bottom为0,所以为Title布局的高度，这时候，Titile布局完全隐藏。
                            float pushedDistance = bottom - titleHeight;
                            //这时候，修改Title栏的topMargin,效果为ListView第二个条目上的sortkey，挤压整个布局的Title栏
                            params.topMargin = (int) pushedDistance;
                            llTitle.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                llTitle.setLayoutParams(params);
                            }
                        }
                    }
                }
                lastFirstVisibleItem = firstVisibleItem;
            }
        });
    }

    /**
     * 获取sort_key的首个字母，如果是英文字母就直接返回，否则返回#
     * @param sortKeyString
     * @return
     */
    private String getSortKey(String sortKeyString) {
        String key = sortKeyString.substring(0, 1).toUpperCase();
        if (key.matches("[A-Z]]")) {
            return key;
        }
        return "#";
    }
}
